//
//  RegisterViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/7/31.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "V4RegisterViewController.h"
#import "SelectWebUrlViewController.h"

@interface V4RegisterViewController ()<UITextFieldDelegate>{
    UIScrollView *scrollBG;
    UITextField *txtMoble;
    UITextField *txtCode;
    UITextField *txtPwd;
    UIButton *btnCode;
    
    BOOL boolBack;
    UIView *viewPwdBG;
    UIButton *subBtn;
    
    UIScrollView*scrollView;
}

@end

@implementation V4RegisterViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self tobeTouMing];
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=NO;
    //注册监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    KKNavigationController *kNav=(KKNavigationController *)self.navigationController;
    kNav.canDragBack=YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
      [self addView];
    
    [txtMoble addTarget:self  action:@selector(passConTextChange:)  forControlEvents:UIControlEventEditingChanged];
    [txtCode addTarget:self  action:@selector(passConTextChange:)  forControlEvents:UIControlEventEditingChanged];
    [txtPwd addTarget:self  action:@selector(passConTextChange:)  forControlEvents:UIControlEventEditingChanged];
}


-(void)passConTextChange:(UITextField*)tf{
    
    if (([txtMoble.text notEmptyOrNull])&&([txtCode.text notEmptyOrNull])&&([txtPwd.text notEmptyOrNull])) {
        
        subBtn.backgroundColor=rgb(223, 171, 34);
    }else{
        subBtn.backgroundColor=rgb(236, 205, 122);
    }
    
    
}

-(void)addView{
    self.view.backgroundColor=zrgbwhiteColor;
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-0)];
    scrollBG=scrollView;
    [self.view addSubview:scrollView];
    scrollView.contentHeight=kTopHeight;
    UILabel*lbTitle=[RHMethods ClableY:scrollView.contentHeight+10 W:kScreenWidth Height:17 font:17 superview:scrollView withColor:nil text:@"请输入手机号"];
    scrollView.contentHeight=lbTitle.frameYH;
    
    {
        UIView*viewContent=[RHMethods viewWithFrame:CGRectMake(0, scrollView.contentHeight+14, kScreenWidth, 60) backgroundcolor:nil superView:scrollView];
        [RHMethods imageviewWithFrame:CGRectMake(20, 31, 12, 18) defaultimage:@"mobicon" supView:viewContent];
        UITextField*tfmoble=[RHMethods textFieldlWithFrame:CGRectMake(46, 20, kScreenWidth-46, 40) font:Font(14) color:nil placeholder:@"请输入手机号" text:@""];
        tfmoble.delegate=self;
        [viewContent addSubview:tfmoble];
        txtMoble=tfmoble;
        
        scrollView.contentHeight=viewContent.frameYH;
        [RHMethods viewWithFrame:CGRectMake(20, viewContent.frameHeight-0.5, kScreenWidth-40, 0.5) backgroundcolor:rgb(229,229,229) superView:viewContent];
        
    }
    {
        UIView*viewContent=[RHMethods viewWithFrame:CGRectMake(0, scrollView.contentHeight+14, kScreenWidth, 60) backgroundcolor:nil superView:scrollView];
        [RHMethods imageviewWithFrame:CGRectMake(20, 31, 13, 15) defaultimage:@"aqicon" supView:viewContent];
        UITextField*tfmoble=[RHMethods textFieldlWithFrame:CGRectMake(46, 20, kScreenWidth-46, 40) font:Font(14) color:nil placeholder:@"请输入验证码" text:@""];
        tfmoble.delegate=self;
        [viewContent addSubview:tfmoble];
        txtCode=tfmoble;
         WSSizeButton*btnyz=[RHMethods buttonWithframe:CGRectMake(kScreenWidth-10-90, 27, 90, 27) backgroundColor:nil text:@"获取验证码" font:14 textColor:zrgborenge radius:3 superview:viewContent];
        btnCode=btnyz;
        [btnCode addTarget:self action:@selector(codeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
        btnyz.layer.borderWidth=1;
        btnyz.layer.borderColor=zrgborenge.CGColor;
        
        
        scrollView.contentHeight=viewContent.frameYH;
        [RHMethods viewWithFrame:CGRectMake(20, viewContent.frameHeight-0.5, kScreenWidth-40, 0.5) backgroundcolor:rgb(229,229,229) superView:viewContent];
        
    }
    {
        UIView*viewContent=[RHMethods viewWithFrame:CGRectMake(0, scrollView.contentHeight+14, kScreenWidth, 60) backgroundcolor:nil superView:scrollView];
        [RHMethods imageviewWithFrame:CGRectMake(20, 31, 12, 15) defaultimage:@"pasicon" supView:viewContent];
        UITextField*tfmoble=[RHMethods textFieldlWithFrame:CGRectMake(46, 20, kScreenWidth-46, 40) font:Font(14) color:nil placeholder:@"请输入密码" text:@""];
        tfmoble.delegate=self;
        [viewContent addSubview:tfmoble];
        txtPwd=tfmoble;
        txtPwd.secureTextEntry=YES;
        
        scrollView.contentHeight=viewContent.frameYH;
        [RHMethods viewWithFrame:CGRectMake(20, viewContent.frameHeight-0.5, kScreenWidth-40, 0.5) backgroundcolor:rgb(229,229,229) superView:viewContent];
        
    }
    
      WSSizeButton*btnlogin=[RHMethods buttonWithframe:CGRectMake(20, scrollView.contentHeight+32, kScreenWidth-40, 40) backgroundColor:rgb(236,205,122) text:@"注册" font:17 textColor:zrgbwhiteColor radius:4 superview:scrollView];
    subBtn=btnlogin;
    
    [subBtn addTarget:self action:@selector(submintButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel*lbtslb=[RHMethods ClableY:0 W:kScreenWidth Height:10 font:10 superview:scrollView withColor:rgb(153,153,153) text:@"轻触上面的“注册”按钮，即表示同意"];
    UILabel*lbxy=[RHMethods ClableY:0 W:kScreenWidth Height:10 font:10 superview:scrollView withColor:rgb(116,147,187) text:@"《鑫开发用户协议》和《隐私声明》"];
    
    

   
    
    lbxy.frameBY=15;
    lbtslb.frameBY=15+10+8;
    [lbxy setColor:rgb(153,153,153) contenttext:@"和"];
    
    
    if ([self.userInfo isEqualToString:@"pwd"]) {
        [btnlogin setTitle:@"重置" forState:UIControlStateNormal];
        lbtslb.hidden=YES;
        lbxy.hidden=YES;
    }else{
    
        {
            UIButton*bxy=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth/2, 20)];
            [scrollView addSubview:bxy];
            bxy.centerY=lbxy.centerY;
            __weak __typeof(self) weakSelf = self;
            [bxy addViewClickBlock:^(UIView *view) {
                [weakSelf pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":@"http://www.xinkaifa2017.com/explain?type=agreement"}];
            }];
            
        }
        {
            UIButton*bxy=[[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth/2, 0, kScreenWidth/2, 20)];
            [scrollView addSubview:bxy];
            bxy.centerY=lbxy.centerY;
            __weak __typeof(self) weakSelf = self;
            [bxy addViewClickBlock:^(UIView *view) {
                [weakSelf pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":@"http://www.xinkaifa2017.com/explain?type=explain"}];
            }];
            
        }
    
    }
    kScrollViewCouldScroll(scrollView);
    [self passConTextChange:nil];
}
#pragma mark button
-(void)codeButtonClicked{
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"哎呀！手机号是不是没输入啊"];
        return;
    }
    [self loadSendCode:@""];
    
}

-(void)backButtonClicked:(id)sender{
    if (boolBack) {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"验证码短信可能略有延迟，确定返回并重新开始？" delegate:self cancelButtonTitle:@"等待" otherButtonTitles:@"返回", nil];
        [alert show];
    }else{
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [super backButtonClicked:sender];
    }
}
-(void)submintButtonClicked{
    DLog(@"确定");//ZKpubseditpass
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    NSString *strCode=txtCode.text;
    if (![strCode notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入验证码"];
        return;
    }
    
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    [dict setValue:strTel forKey:@"mobile"];
    [dict setValue:strCode forKey:@"code"];
    NSString *strPwd=txtPwd.text;
//    if (![self.userInfo isEqualToString:@"other"]) {
//        if (![strPwd notEmptyOrNull]) {
//            [SVProgressHUD showImage:nil status:@"请输入密码"];
//            return;
//        }
//        [dict setValue:strPwd forKey:@"password"];
//    }
    
//    if (![self.userInfo isEqualToString:@"other"]) {
        if (![strPwd notEmptyOrNull]) {
            [SVProgressHUD showImage:nil status:@"请输入密码"];
            return;
        }
        [dict setValue:strPwd forKey:@"password"];
//    }
    NSString *strUrl=XKFV4welcomeregister;
    if ([self.userInfo isEqualToString:@"pwd"]) {
        strUrl=XKFV4welcomeforgetpassword;
    }else if ([self.userInfo isEqualToString:@"other"]){
        strUrl=XKFV4welcomebindmobile;
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"openid"];
        if ([[self.otherInfo valueForJSONKey:@"openid"] notEmptyOrNull]) {
            
            [dict setValue:[self.otherInfo valueForJSONStrKey:@"openid"] forKey:@"openid"];
        }
        
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"type"] forKey:@"type"];
    }
    [NetEngine createPostAction:strUrl withParams:dict onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
            if ([self.userInfo isEqualToString:@"pwd"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [super backButtonClicked:nil];
                });
            }else if ([self.userInfo isEqualToString:@"other"]){
                NSDictionary *userDict = [resData objectForJSONKey:@"data"];
                [[Utility Share] setUserAccount:strTel];
                [[Utility Share] setUserPwd:strPwd];
                [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
                [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
                //                [[Utility Share] setUserInfo:userDict];
                [[Utility Share] saveUserInfoToDefault];
                [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[Utility Share] hiddenLoginAlert:YES];
                });
            }else{
                //注册
                NSDictionary *userDict = [resData objectForJSONKey:@"data"];
                [[Utility Share] setUserAccount:strTel];
                [[Utility Share] setUserPwd:strPwd];
                [[Utility Share] setUserId:[userDict valueForJSONStrKey:@"uid"]];
                [[Utility Share] setUserToken:[userDict valueForJSONStrKey:@"token"]];
                //                [[Utility Share] setUserInfo:userDict];
                [[Utility Share] saveUserInfoToDefault];
                [[Utility Share] setUserIsADD:[[userDict valueForJSONStrKey:@"type"] isEqualToString:@"4"]];//type    int        用户类型(1
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[Utility Share] hiddenLoginAlert:YES];
                });
            }
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
    
    boolBack=NO;
}

-(void)loadSendCode:(NSString *)strCid{
    NSString *strTel=txtMoble.text;
    if (![strTel notEmptyOrNull]) {
        [SVProgressHUD showImage:nil status:@"请输入手机号"];
        return;
    }
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
    [dict setValue:strTel forKey:@"mobile"];
    
    NSString *strUrl=XKFV4welcomeregistercode;
    if ([self.userInfo isEqualToString:@"pwd"]) {
        strUrl=XKFV4welcomeforgetcode;
    }else if ([self.userInfo isEqualToString:@"other"]){
        strUrl=XKFV4welcomebindcode;
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"id"] forKey:@"openid"];
        if ([[self.otherInfo valueForJSONKey:@"openid"] notEmptyOrNull]) {
            
            [dict setValue:[self.otherInfo valueForJSONStrKey:@"openid"] forKey:@"openid"];
        }
        
        [dict setValue:[self.otherInfo valueForJSONStrKey:@"type"] forKey:@"type"];
    }
    [NetEngine createHttpActionFixed:strUrl withCache:NO withParams:dict withMask:SVProgressHUDMaskTypeNone onCompletion:^(id resData, BOOL isCache) {
        DLog(@"__resData____%@",resData);
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            if ([self.userInfo isEqualToString:@"other"] &&
                [[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"pwd"] isEqualToString:@"0"]){
                viewPwdBG.hidden=NO;
//                subBtn.frameY=YH(viewPwdBG)+20;
//                [scrollBG setContentSize:CGSizeMake(kScreenWidth, YH(subBtn)+20)];
            }
            boolBack=YES;
            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
            
//            [btnCode setBackgroundColor:RGBACOLOR(150, 150, 150, 1)];
            btnCode.userInteractionEnabled=NO;
            //            [self performSelector:@selector(updateButtonTitle:) withObject:@"60" afterDelay:0];
            [self performSelector:@selector(updateButtonTitle:) withObject:[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"codetime"] afterDelay:0];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    } onError:^(NSError *error) {
        [SVProgressHUD showImage:nil status:alertErrorTxt];
    }];
    //
}

-(void)updateButtonTitle:(NSString *)str{
    float aflote=[str floatValue];
    DLog(@"________________()()()()()(");
    [btnCode setTitle:[NSString stringWithFormat:@"%.0f秒",aflote] forState:UIControlStateNormal];
    if (aflote<=1) {
        [self performSelector:@selector(yanZM_date) withObject:nil afterDelay:1.0];
    }else{
        aflote--;
        [self performSelector:@selector(updateButtonTitle:) withObject:[NSString stringWithFormat:@"%f",aflote] afterDelay:1.0];
    }
}

-(void)yanZM_date{
    DLog(@"延迟——————禁止验证码按钮");
    [btnCode setTitle:@"重新获取" forState:UIControlStateNormal];
//    [btnCode setBackgroundColor:rgbpublicColor];
    btnCode.userInteractionEnabled=YES;
}
#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        boolBack=NO;
        [super backButtonClicked:nil];
    }
}

#pragma mark selector
-(void)handleKeyboardDidShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;
    CGFloat distanceToMove = kbSize.height;
    NSLog(@"---->动态键盘高度:%f",distanceToMove);
    
    [UIView animateWithDuration:0.3 animations:^{
        scrollBG.frame=CGRectMake(X(scrollBG), Y(scrollBG), W(scrollBG),self.view.frame.size.height- Y(scrollBG)-distanceToMove);
        
        
    }];
}
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.3 animations:^{
        scrollBG.frame=CGRectMake(0, Y(scrollBG), kScreenWidth,kScreenHeight);
    }];
}//

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
